import time
from selenium import webdriver
from selenium.webdriver import Keys
from selenium.webdriver.support.wait import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

driver = webdriver.Chrome()
driver.get("https://www.baidu.com")
driver.maximize_window()
wait = WebDriverWait(driver, 10,0.2)
search = wait.until(EC.presence_of_element_located((By.ID,'chat-textarea')))
search.send_keys("中国刑法", Keys.ENTER)

xingfa = wait.until(EC.presence_of_element_located((By.CLASS_NAME,'tts-b-hl')))
xingfa.click()
time.sleep(2)

driver.switch_to.window(driver.window_handles[-1])
total_height = driver.execute_script("return document.body.scrollHeight")
viewport_height = driver.execute_script("return window.innerHeight;")
scroll_step = viewport_height
current_position = 0
while current_position < total_height:
    driver.execute_script(f"window.scrollTo(0, {current_position});")
    current_position += scroll_step
    time.sleep(0.5)
print("此页面浏览完毕，即将返回顶部")
driver.execute_script("window.scrollTo(0, 0);")
input("按回车开始下载源代码")

page_source = driver.page_source[:5000]
print("-------源码为--------")
print(page_source)
with open("刑法.html","w",encoding="utf-8") as f:
    f.write(page_source)


input("回车退出")
driver.quit()